<template>
  <div class="promotions" :class="isDark ? 'is-dark' : 'is-light'" v-if="!piniaSystem.getIsH5">
    <div class="promotions-banner">
      <div class="promotions-banner__info">
        <div class="promotions-banner__monthly">{{t('activityHome.monthly')}}</div>
        <div class="promotions-banner__lucky">{{t('activityHome.luckySpins')}}</div>
        <div class="promotions-banner__surprises">{{t('activityHome.surprises')}}</div>
      </div>
    </div>
    <div class="promotions-tabs">
      <ZTab
        v-model:navs="navs"
        v-model:active="navsActive"
        layout="left"
        @change="handleTab"
      >
        <template #toolbar>
          <el-input v-model="form.name" size="small" :prefix-icon="Search" @blur="getPlayPageActivityList" @keydown.enter.native="getPlayPageActivityList" placeholder="" />
        </template>
      </ZTab>
    </div>
    <div class="promotions-content">
      <div class="promotions-content__item" v-for="item in lists" :key="item.id">
        <div class="promotions-content-wrapper" @click="openInfo(item)">
          <img v-zlazy="item.currentLangPic.content" alt="">
          <div class="promotions-content__title">
            <h3>{{item.currentLangTitle.content}}</h3>
            <h4>{{parseTime(item.activityStartTime, '{y}-{m}-{d}')}} — {{ parseTime(item.activityEndTime, '{y}-{m}-{d}') }}</h4>
          </div>
        </div>
      </div>
    </div>
    <div class="system-main-footer">
      <span>copyright ©  Mini.Bet 2023 All rights reserved.</span>
      <span>Mini.Bet is operated by Bridge Technologies B.V., with the registration number of 160264 and the registered office address of Dr. M.J. Hugenholtzweg 25, Cura ç ao. It is licensed and authorized by the government of Cura ç ao. The main license is # 8048/JAZ 2022 - 024 Operations issued to Antillephone N.V. The payment agent is Bridge Technologies (Cyrus) Limited, with the registered address of 47 Strovolos Avenue, 5th floor, Curista, Strovolos 2018, Nicosia, Cyprus, Registration No. HE 440867</span>
    </div>
  </div>
  <div class="promotions-h5" :class="isDark ? 'is-dark' : 'is-light'" v-if="piniaSystem.getIsH5">
    <div class="promotions-banner-h5">
      <div class="promotions-banner-h5__info">
        <div class="promotions-banner-h5__monthly">{{t('activityHome.monthly')}}</div>
        <div class="promotions-banner-h5__lucky">{{t('activityHome.luckySpins')}}</div>
        <div class="promotions-banner-h5__surprises">{{t('activityHome.surprises')}}</div>
      </div>
      <img :src="images.activityH5" alt="">
    </div>
    <div class="promotions-h5-search">
      <i-majesticons-search-line />
      <input type="text" v-model="form.name" @blur="getPlayPageActivityList">
      <div class="promotions-h5-search__selector" @click="typePickerShow = true">{{ pickerLabel.label }}</div>
      <van-popup v-model:show="typePickerShow" round position="bottom">
        <van-picker
          :columns="navs"
          @confirm="onConfirmType"
          @cancel="typePickerShow = false"
          v-model="selectedValues"
          :option-height="`100rem`"
        >
          <template #option="scope">
            {{ scope.label }}
          </template>
        </van-picker>
      </van-popup>
    </div>
    <div class="promotions-content-h5">
      <div class="promotions-content-h5__item" v-for="item in lists" :key="item.id" @click="openInfo(item)">
        <div class="promotions-content-h5-wrapper">
          <img v-zlazy="item.currentLangPic.content" alt="">
          <div class="promotions-content-h5__title">
            <h3>{{item.currentLangTitle.content}}</h3>
            <h4>{{parseTime(item.activityStartTime, '{y}-{m}-{d}')}} — {{ parseTime(item.activityEndTime, '{y}-{m}-{d}') }}</h4>
          </div>
        </div>
      </div>
    </div>
    <div class="system-main-footer">
      <span>copyright ©  Mini.Bet 2023 All rights reserved.</span>
      <span>Mini.Bet is operated by Bridge Technologies B.V., with the registration number of 160264 and the registered office address of Dr. M.J. Hugenholtzweg 25, Cura ç ao. It is licensed and authorized by the government of Cura ç ao. The main license is # 8048/JAZ 2022 - 024 Operations issued to Antillephone N.V. The payment agent is Bridge Technologies (Cyrus) Limited, with the registered address of 47 Strovolos Avenue, 5th floor, Curista, Strovolos 2018, Nicosia, Cyprus, Registration No. HE 440867</span>
    </div>
  </div>
  <Dialog v-model:visible="dialogConfig.show" v-model:title="dialogConfig.title" :width="dialogConfig.width" :headerFixed="dialogConfig.headerFixed">
    <div class="promotions-dialog">
      <div class="promotions-dialog-box">
        <h4 class="promotions-dialog__title">{{itemInfo.currentLangTitle.content}}</h4>
        <img class="promotions-dialog__img" v-zlazy="itemInfo.currentLangPic.content" alt="">
        <div class="promotions-dialog__info">
          {{t('activityHome.activityTime')}}:
          <span>{{parseTime(itemInfo.activityStartTime, '{y}-{m}-{d}')}} — {{ parseTime(itemInfo.activityEndTime, '{y}-{m}-{d}') }}</span>
        </div>
        <div class="promotions-dialog__info">
          {{t('activityHome.activityName')}}:
          <span>{{itemInfo.currentLangTitle.content}}</span>
        </div>
        <div class="promotions-dialog__content" v-html="itemInfo.currentLangContent.activityContent">
        </div>
      </div>
      <div v-if="showJoinActivity" class="bottomOperate">
        <div v-if="joinActivity" class="activityNo" @click="hasActivityed">{{ t('activityHome.hasJoined') }}</div>
        <div v-else="joinActivity" class="operateBtn" @click="handleActivity(itemInfo.activityId)">{{ t('activityHome.joinActivity') }}</div>
      </div>
    </div>
  </Dialog>
</template>

<script setup lang="ts">
import { isDark, toggleDark } from '@/utils/dark';
import system from '@/store/system';
import promotionsApi from '@/api/modules/promotions';
import { parseTime } from '@/utils/format';
import { Search } from '@element-plus/icons-vue'
import nocache from '@/store/nocache';
import { showNotify } from 'vant';

const global:any = getCurrentInstance()?.appContext.config.globalProperties;
const piniaSystem = system();
const piniaNocache = nocache();
const { t } = useI18n();

const images: any = reactive({
  activityH5: new URL(`../../assets/images/promotions/activityH5.svg`, import.meta.url).href,
});

const data: any = reactive({
  form: {},
  navs: [],
  navsActive: "all",
  currentNav: {},
  lists: [],
  dialogConfig: {
    show: false,
    title: "",
    width: 450,
    headerFixed: false
  },
  typePickerShow: false,
  itemInfo: {},
  selectedValues: [],
  pickerLabel: '',
  showJoinActivity: false,
  joinActivity: false
});
const {
  form,
  navs,
  navsActive,
  currentNav,
  lists,
  dialogConfig,
  itemInfo,
  typePickerShow,
  selectedValues,
  pickerLabel,
  showJoinActivity,
  joinActivity
} = toRefs(data);

// 监听语言切换
watch(
  () => piniaSystem.getLang.code,
  (val, preVal) => {
    handleLangName();
    hanldeLangForLists();
  },
  { immediate: false, deep: true },
);

// 打开详情
const openInfo = (item: any) => {
  itemInfo.value = item;
  dialogConfig.value.show = true;
  piniaSystem.getIsH5 ? (dialogConfig.value.width = '100%') : (dialogConfig.value.width = 450);
  if(item.activityStatus == 1){
    showJoinActivity.value = true;
    getUserJoinActivity(item.activityId);
  }else{
    showJoinActivity.value = false;
  }
}

// 查询活动状态
const getUserJoinActivity = (activityId: string) => {
  promotionsApi.getUserJoinActivity({
    activityId: activityId
  }).then((response:any)=>{
    console.log('查询活动状态', response)
    if(response.code === 200){
      joinActivity.value = response.data.join
    }
  })
}

// 已经参加
const hasActivityed = () => {
  showNotify({ type: "warning", message: `You have participated in other activities and cannot participate in this activity` });
}

// 参加
const handleActivity = (activityId: string) => {
  promotionsApi.addUserJoinActivity({
    activityId: activityId
  }).then((response:any)=>{
    console.log(response)
    if(response.code === 200){
      getUserJoinActivity(activityId);
      global.message(response.msg)
    }else {
      global.message(response.msg, {
        type: 'warning',
      })
    }
  })
}

// 切换tab
const handleTab = ({nav}: any) => {
  if(currentNav.value.code !== nav.code){
    currentNav.value = nav;
    getPlayPageActivityList();
  }
}

// h5选择
const onConfirmType = ({selectedOptions}: any) => {
  currentNav.value.code = selectedOptions[0].code;
  getPlayPageActivityList();
  typePickerShow.value = false;
  pickerLabel.value = selectedOptions[0];
}

// 查询列表
const getPlayPageActivityList = () => {
  promotionsApi.getPlayPageActivityList({
    activityClass: currentNav.value.code,
    name: form.value.name,
  }).then((response:any)=>{
    console.log('查询结果', response)
    lists.value = response.rows || [];
    hanldeLangForLists();
  });
}
getPlayPageActivityList();

// 改变列表国际化
const hanldeLangForLists = () => {
  lists.value.forEach((element: any) => {
    element.currentLangContent = element.listContent.find((im:any)=>{
      return im.languageCode === piniaSystem.getLang.code;
    }) || {};
    element.currentLangPic = element.listPic.find((im:any)=>{
      return im.languageCode === piniaSystem.getLang.code;
    }) || {};
    element.currentLangTitle = element.listTitle.find((im:any)=>{
      return im.languageCode === piniaSystem.getLang.code;
    }) || {};
  });
}

// 促销tab列表
const getBackWaterTermConfig = () => {
  promotionsApi.getBackWaterTermConfig({}).then((response:any)=>{
    if(response.code === 200){
      navs.value = [{}].concat(response.data) || [{}];
      handleLangName();
    }
  })
}
getBackWaterTermConfig();

// 国际化切换 mmp
const handleLangName = () => {
  navs.value.shift();
  navs.value.map((im:any)=>{
    const element = im.languageChildren.find((ele:any)=>{
      return ele.languageType === piniaSystem.getLang.code;
    });
    im.text = im.label = element && element.languageName || im.name;
    im.value = im.active = im.code;
  });
  const defaultAll = {
    label: t('notice.text11'),
    code: '',
    active: 'all',
    languageChildren: []
  };
  navs.value = [defaultAll, ...navs.value];
  pickerLabel.value = navs.value.length > 0 && navs.value[0];
}

onMounted(()=>{
  if(piniaSystem.getIsH5){
    piniaNocache.setIsOpenHeader(false);
  }
});

onUnmounted(()=>{
  piniaNocache.setIsOpenHeader(true);
});
</script>

<style lang="scss" scoped>
@import url(./index.scss);
</style>
